Introduction

This document is intended to be both a tutorial and a reference guide. While it does not list all possible use cases, it should give a good overview of the principal functionality. Python support was first introduced in QGIS 0.9. Today, there are several ways to use Python in QGIS Desktop, they are covered in the following sections:

  • Issue commands in the Python console within QGIS
  • Create and use plugins
  • Automatically run Python code when QGIS starts
  • Create custom applications based on the QGIS API

QGIS provides an integrated Python console for scripting. It can be opened from the menu Plugins ‣ Python Console

Loading Projects

To load a project into the current QGIS application you need to create a QgsProject instance() object and call its read() method passing the path of the project to be loaded:

from qgis.core import QgsProject project = QgsProject.instance()) print(project.fileName() project.read('/home/user/projects/my_other_qgis_project.qgs') print(project.fileName())

If you need to make modifications to the project (for example to add or remove some layers) and save your changes, call the write() method of your project instance.

Loading Layers

QGIS recognizes vector and raster layers. Additionally, custom layer types are available, but we are not going to discuss them here. To load a vector layer, specify layer’s data source identifier, name for the layer and provider’s name:

layer = QgsVectorLayer(data_source, layer_name, provider_name) if not layer.isValid(): print("Layer failed to load!")

PostGIS database — data source is a string with all information needed to create a connection to PostgreSQL database. QgsDataSourceUri class can generate this string for you. Note that QGIS has to be compiled with Postgres support, otherwise this provider isn’t available: uri = QgsDataSourceUri() # set host name, port, database name, username and password uri.setConnection("localhost", "5432", "dbname", "johny", "xxx") # set database schema, table name, geometry column and optionally/span> # subset (WHERE clause) uri.setDataSource("public", "roads", "the_geom", "cityid = 2643") vlayer = QgsVectorLayer(uri.uri(False), "layer name you like", "postgres")

SpatiaLite database — Similarly to PostGIS databases, QgsDataSourceUri can be used for generation of data source identifier: uri = QgsDataSourceUri() uri.setDatabase('/home/martin/test-2.3.sqlite') schema = '' table = 'Towns' geom_column = 'Geometry' uri.setDataSource(schema, table, geom_column) display_name = 'Towns' vlayer = QgsVectorLayer(uri.uri(), display_name, 'spatialite')

Using Raster Layers

For accessing raster files, GDAL library is used. It supports a wide range of file formats. In case you have troubles with opening some files, check whether your GDAL has support for the particular format (not all formats are available by default). To load a raster from a file, specify its filename and display name:

rlayer = QgsRasterLayer("/path/to/raster/file.tif", "my layer" if not rlayer.isValid(): print("Layer failed to load!")

Similarly to vector layers, raster layers can be loaded using the addRasterLayer function of the QgisInterface:

iface.addRasterLayer("/path/to/raster/file.tif", "layer name you like")

Using Vector Layers

You can retrieve information about the fields associated with a vector layer by calling fields() on a QgsVectorLayerinstance: for field in layer.fields(): print(field.name(), field.typeName())

Attributes can be referred to by their name: print(feature['name']) Alternatively, attributes can be referred to by index. This is a bit faster than using the name. For example, to get the first attribute: print(feature[0])

Lorem ipsum dolor sit amet consectetur adipisicing elit. Laudantium mollitia cupiditate ipsum! Distinctio fuga commodi sit impedit cupiditate quidem, voluptate incidunt, nisi rerum obcaecati vitae esse nostrum consectetur in qui veritatis! Laudantium possimus atque, quos voluptatibus asperiores quibusdam veritatis sit minus adipisci fuga ipsam inventore quae eius optio, placeat repellat magnam. Ea veritatis accusantium labore aspernatur commodi ullam totam nisi fuga consequatur neque hic incidunt architecto officiis, vero perspiciatis ad est rerum exercitationem consequuntur saepe rem nam enim impedit! At eos, eius incidunt tempore animi nisi laborum exercitationem iure commodi facilis aliquid quod natus vel autem adipisci soluta sequi illum suscipit, iusto in. Accusantium pariatur eligendi ullam odio ratione aliquam quibusdam, nemo quo est natus modi, qui ducimus! Consectetur, voluptatum quibusdam, rem quam ducimus dolor beatae doloremque molestiae eveniet illo labore esse? Debitis vero reiciendis velit obcaecati ad, deleniti quaerat fugit, nostrum repellat corrupti quia doloribus ipsam deserunt perferendis odio?

Geometry Handling

Points, linestrings and polygons that represent a spatial feature are commonly referred to as geometries. In QGIS they are represented with the QgsGeometry class. Sometimes one geometry is actually a collection of simple (single-part) geometries. Such a geometry is called a multi-part geometry. If it contains just one type of simple geometry, we call it multi-point, multi-linestring or multi-polygon. For example, a country consisting of multiple islands can be represented as a multi-polygon.

  • Geometry Construction
  • Access to Geometry
  • Geometry Predicates and Operations

There are several options for creating a geometry:

  • From Coordinates: gPnt = QgsGeometry.fromPointXY(QgsPointXY(1,1)) gLine = QgsGeometry.fromPolyline([QgsPoint(1, 1), QgsPoint(2, 2)]) gPolygon = QgsGeometry.fromPolygonXY([[QgsPointXY(1, 1), QgsPointXY(2, 2), QgsPointXY(2, 1)]])
  • from well-known binary (WKB): >>> g = QgsGeometry() >>> wkb = bytes.fromhex("010100000000000000000045400000000000001440") >>> g.fromWkb(wkb) >>> g.asWkt() 'Point (42 5)'
  • from well-known text (WKT): gem = QgsGeometry.fromWkt("POINT(3 4)")

Lorem ipsum dolor sit amet consectetur adipisicing elit. Velit eaque doloribus veritatis quod praesentium sit eligendi unde officiis assumenda explicabo facilis sapiente inventore laborum sequi at iste, doloremque dolor, impedit veniam? Distinctio ullam animi quis et ut quidem, architecto facilis incidunt. Eos veniam laudantium quibusdam dignissimos iste praesentium rem, sapiente ipsa soluta dolore totam natus maiores similique temporibus suscipit. Necessitatibus quisquam autem odio magnam, voluptatem ad aliquam perspiciatis vero odit iure sequi, maxime, expedita consectetur corporis nesciunt! Maxime minus reiciendis eos asperiores quia hic earum voluptatibus temporibus. Laborum ut cum similique dolorum repellat tempore vel, soluta dicta asperiores aut corrupti dolore, expedita molestias? Consequatur, ex modi magni, doloribus commodi impedit deleniti alias ipsum tempore necessitatibus et, eligendi ipsam sint incidunt consectetur qui praesentium placeat perspiciatis itaque dicta unde! Unde ipsam enim laudantium animi inventore laborum delectus, impedit porro minus dignissimos iure, odio minima facere? Rem ea sapiente pariatur laudantium reiciendis?

Map Rendering

There are generally two approaches when input data should be rendered as a map: either do it quick way using QgsMapRenderer or produce more fine-tuned output by composing the map with QgsComposition class and friends.

If you have more than one layer and they have a different CRS, the simple example above will probably not work: to get the right values from the extent calculations you have to explicitly set the destination CRS and enable OTF reprojection as in the example below (only the renderer configuration part is reported)

# set layer set layers = QgsMapLayerRegistry.instance().mapLayers() lst = layers.keys() render.setLayerSet(lst)

Print layout is a very handy tool if you would like to do a more sophisticated output than the simple rendering shown above. It is possible to create complex map layouts consisting of map views, labels, legend, tables and other elements that are usually present on paper maps. The layouts can be then exported to PDF, raster images or directly printed on a printer. The layout consists of a bunch of classes. They all belong to the core library. QGIS application has a convenient GUI for placement of the elements, though it is not available in the GUI library. If you are not familiar with Qt Graphics View framework, then you are encouraged to check the documentation now, because the layout is based on it. Also check the Python documentation of the implementation of QGraphicView mapRenderer = iface.mapCanvas().mapRenderer() c = QgsComposition(mapRenderer) c.setPlotStyle(QgsComposition.Print)

  • Arrow
  • Picture
  • Basic Shape
  • Nodes based shape: polygon = QPolygonF() polygon.append(QPointF(0.0, 0.0)) composerPolygon = QgsComposerPolygon(polygon, c) props = {} props["joinstyle"] = "miter"
  • Table
  • Scale bar
  • Scale bar
  • Map